<%@page import="java.io.FileNotFoundException"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.zip.ZipEntry"%>
<%@page import="java.util.Enumeration"%>
<%@page import="java.util.zip.ZipFile"%>
<%@page import="java.util.zip.CRC32"%>
<%@page import="java.util.zip.ZipOutputStream"%>
<%@page import="java.util.zip.CheckedOutputStream"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.util.List"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.*"%>
<%@page import="org.apache.commons.fileupload.servlet.*"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="org.apache.commons.fileupload.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
//tomcat服务服务名称，用于重启tomcat
String SER_TOMCAT = "chenkTomcat8";
String password = "chenksoft!!!";

String PATH_PROJECT = "";
//这个路径相对当前应用的目录
PATH_PROJECT = getServletContext().getRealPath("");
if (!PATH_PROJECT.endsWith(File.separator)) {
	PATH_PROJECT += File.separator;
}
String UPLOAD_DIRECTORY = "upload";
//构造临时路径来存储上传的文件


String uploadPath = PATH_PROJECT + UPLOAD_DIRECTORY;

// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
	uploadDir.mkdir();
}
// 上传配置
int MEMORY_THRESHOLD   = 1024 * 1024 * 50;  // 50MB
int MAX_FILE_SIZE      = 1024 * 1024 * 200; // 200MB
int MAX_REQUEST_SIZE   = 1024 * 1024 * 200; // 200MB
String m = request.getParameter("m");
if(m==null){
	
}else if(m.equals("restartServer")&&session.getAttribute("lock")!=null&&session.getAttribute("lock").equals("1")){
	System.out.println("restartServer");
	//1、生成bat文件，2.执行bat文件
	String log = uploadPath + File.separator+"log.log";
	String bat = "echo %date%%time% stop server >>"+log+" \n";
	bat += "net stop "+SER_TOMCAT+" >> "+log+" \n";
	bat += "echo %date%%time%  start server >>"+log+" \n";
	bat += "net start "+SER_TOMCAT+" >> "+log+" \n";
	String dstfile = uploadPath + File.separator + "restartTomcat.bat";
	String filecontent = bat;
	File file = new File(dstfile);
	if(file.exists()){
		//forceDelete(file);
	}
	if (!file.exists()) {
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	FileOutputStream fos = null;
	try {
		fos = new FileOutputStream(dstfile);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}

    OutputStreamWriter write = null;
	try {
		write = new OutputStreamWriter(fos,"UTF-8");
	} catch (Exception e) {
		e.printStackTrace();
	}
      BufferedWriter writer = new BufferedWriter(write);
      try {
		writer.write(filecontent);
	} catch (IOException e) {
		e.printStackTrace();
	}
      try {
		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
	} 
    String strcmd = "cmd /c  "+dstfile;
    Runtime.getRuntime().exec(strcmd);
	return;
}else if(m.equals("resetSession")){
	session.removeAttribute("message");
	return ;
}else if(m.equals("key")){
	int sum = session.getAttribute("click_sum")==null?0:Integer.parseInt(session.getAttribute("click_sum").toString());
	if(sum>=20){
		return;
	}
	
	session.setAttribute("click_sum", sum+1);
	String key = request.getParameter("key");	
	if(key!=null&&key.equals(password)){
		session.setAttribute("lock", "1");
	}
	return;
}
if ((!ServletFileUpload.isMultipartContent(request))) {
	//如果没有文件上传
} else {
	// 配置上传参数
	DiskFileItemFactory factory = new DiskFileItemFactory();
	// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
	factory.setSizeThreshold(MEMORY_THRESHOLD);
	// 设置临时存储目录
	factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

	ServletFileUpload upload = new ServletFileUpload(factory);

	// 设置最大文件上传值
	upload.setFileSizeMax(MAX_FILE_SIZE);

	// 设置最大请求值 (包含文件和表单数据)
	upload.setSizeMax(MAX_REQUEST_SIZE);

	// 中文处理
	upload.setHeaderEncoding("UTF-8");

	

	try {
		// 解析请求的内容提取文件数据
		@SuppressWarnings("unchecked")
		List<FileItem> formItems = upload.parseRequest(request);

		if (formItems != null && formItems.size() > 0&&session.getAttribute("lock")!=null&&session.getAttribute("lock").equals("1")) {
			// 迭代表单数据
			for (FileItem item : formItems) {
				// 处理不在表单中的字段
				if (!item.isFormField()) {					
					String fileName = new File(item.getName()).getName();
					String filePath = uploadPath + File.separator + fileName;
					File storeFile = new File(filePath);
					// 在控制台输出文件的上传路径
					System.out.println(PATH_PROJECT);
					System.out.println(filePath);
					// 保存文件到硬盘
					item.write(storeFile);
					session.setAttribute("message", "文件上传成功!");
					//解压文件到项目路径
					String topath = PATH_PROJECT;
					String frompath = filePath;
					ZipFile zf = new ZipFile(new File(frompath));
					InputStream inputStream;
					Enumeration en = zf.entries();
					while (en.hasMoreElements()) {
						ZipEntry zn = (ZipEntry) en.nextElement();
						if (!zn.isDirectory()) {
							inputStream = zf.getInputStream(zn);
							File f = new File(topath + zn.getName());
							File file = f.getParentFile();
							file.mkdirs();
							System.out.println(zn.getName() + "---" + zn.getSize());

							FileOutputStream outputStream = new FileOutputStream(topath + zn.getName());
							int len = 0;
							byte bufer[] = new byte[1024];
							while (-1 != (len = inputStream.read(bufer))) {
								outputStream.write(bufer, 0, len);
							}
							outputStream.close();
						}
					}
					session.setAttribute("message", "更新成功，请重启tomcat服务!");
				} else {

				}
			}
		}
	} catch (Exception ex) {
		session.setAttribute("message", "错误信息: " + ex.getMessage());
	}
	response.setHeader("enctype", "");
	// 跳转到 message.jsp
	response.sendRedirect("update.jsp");
}
%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>更新web服务</title>
</head>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest)
{
	// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
	xmlhttp=new XMLHttpRequest();
}
else
{
	// IE6, IE5 浏览器执行代码
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		
	}
}
xmlhttp.open("GET","update.jsp?m=resetSession",true);
xmlhttp.send();
function restartTomcat(){
	xmlhttp.open("GET","update.jsp?m=restartServer",true);
	xmlhttp.send();
	alert("重启命令已发出！");
}
if("${lock}"!="1"){
	var str = prompt("请输入密码:","");
	if (str != null){
		xmlhttp.open("GET","update.jsp?m=key&key="+str,true);
		xmlhttp.send();
		location.href=location.href;
	}else{
		//location.href=location.href;
	}
}
</script>
<body>
<h3>${message}</h3>
<form action="update.jsp" method="post" enctype="multipart/form-data">
更新文件(必须为zip文件)：<input name="file" type="file" />
<br/>
<input type="submit"/>
</form>
<button onclick="restartTomcat()">重启tomcat</button>
</body>

</html>